package com.tidc.downprovider.config;



import com.tidc.downprovider.exception.LLGAuthenticationEntryPoint;
import com.tidc.downprovider.message.AuthExceptionEntryPoint;
import com.tidc.downprovider.message.CustomAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * @ClassNmae Auth2Config
 * @Description TODO
 * @Author 冯涛滔
 **/
@Configuration
@EnableResourceServer//这个配置相当于securityConfig
public class Auth2Config extends ResourceServerConfigurerAdapter {
	private final CustomAccessDeniedHandler customAccessDeniedHandler;
@Autowired
private RedisConnectionFactory redisConnectionFactory;
	//	授权失败处理
	@Autowired
	public Auth2Config(CustomAccessDeniedHandler customAccessDeniedHandler) {
		this.customAccessDeniedHandler = customAccessDeniedHandler;
	}

	/**
	 * 验证token失败
	 * 设置一个token校验失败的处理器
	 *
	 * @param resources resources
	 * @throws Exception resources
	 */
	@Override
	public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
		resources.tokenServices(tokenServices());
		resources.authenticationEntryPoint(new LLGAuthenticationEntryPoint());
		resources.authenticationEntryPoint(new AuthExceptionEntryPoint())
				.accessDeniedHandler(customAccessDeniedHandler);
		resources.tokenStore(tokenStore());
	}
	@Bean
	public TokenStore tokenStore(){

		return new RedisTokenStore(redisConnectionFactory);
	}
	@Primary
	@Bean
	public RemoteTokenServices tokenServices() {
		final RemoteTokenServices tokenService = new RemoteTokenServices();
		tokenService.setCheckTokenEndpointUrl("http://localhost:5123/oauth/check_token");
		tokenService.setClientId("TIDC");
		tokenService.setClientSecret("computer");
		return tokenService;
	}

	@Override
	public void configure(HttpSecurity http) throws Exception {
		//全部放行
		http.authorizeRequests().anyRequest().permitAll();
		http.sessionManagement()
				.and().cors()
				.and().csrf().disable();
	}


}